import { RequestHeader } from '@/enums/request';
import axios from 'axios';
import type { AxiosResponse, InternalAxiosRequestConfig, RawAxiosRequestHeaders } from 'axios';
import qs from 'qs';

const instance = axios.create({
  baseURL: 'http://localhost:8080/api/v1',
  headers: {
    [RequestHeader.CONTENT_TYPE]: [RequestHeader.CONTENT_TYPE_APPLICATION_JSON],
  },
  paramsSerializer: {
    serialize: params => qs.stringify(params, { arrayFormat: 'brackets', skipNulls: true })
  },
  responseType: 'json',
  timeout: 15000,
  timeoutErrorMessage: '请求超时，请稍后重试',
});

instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  return config;
});

instance.interceptors.response.use((response: AxiosResponse<ApiResponse>) => {
  return response;
});

export function get<T = any>(url: string, params: Recordable = {}, headers: RawAxiosRequestHeaders = {}) {
  return instance
    .get<ApiResponse<T>>(url,{
      headers,
      params,
    },
    )
    .then(response => response.data);
}

export function post<T = any, D = Recordable>(
  url: string,
  data: D,
  params: Recordable = {},
  headers: RawAxiosRequestHeaders = {},
) {
  return instance
    .post<ApiResponse<T>, AxiosResponse<ApiResponse<T>, D>, D>(url, data, {
      params,
      headers,
    })
    .then(response => response.data);
}

export function put<T = any, D = Recordable>(
  url: string,
  data: D,
  params: Recordable = {},
  headers: RawAxiosRequestHeaders = {},
) {
  return instance
    .put<ApiResponse<T>, AxiosResponse<ApiResponse<T>, D>, D>(url, data, {
      params,
      headers,
    })
    .then(response => response.data);
}
